package com.atguigu.edu.app.func;

import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;


@FunctionHint(output = @DataTypeHint("ROW<keyword STRING>"))
public class UDTFKeywordsFunc extends TableFunction<Row> {

    public void eval(String str){
        List<String> stringList = flatWord(str);
        for (String s : stringList) {
            collect(Row.of(s));
        }
    }

    public static List<String> flatWord(String keywords){
        StringReader stringReader = new StringReader(keywords);
        ArrayList<String> result = new ArrayList<>();//用来放拆分后的结果
        // 使用ik分词器
        IKSegmenter ikSegmenter = new IKSegmenter(stringReader, true);
        Lexeme lexeme = null;

        try{
            while ((lexeme = ikSegmenter.next()) != null){
                result.add(lexeme.getLexemeText());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

}
